<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.5.1/github-markdown.min.css" >
    <!-- Code highlight -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <!-- and it's easy to individually load additional languages -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/go.min.js"></script>
    <style>
      .markdown-body {
        box-sizing: border-box;
        min-width: 200px;
        max-width: 980px;
        margin: 0 auto;
        padding: 45px;
      }

      @media (max-width: 767px) {
        .markdown-body {
          padding: 15px;
        }
      }
    </style>
    <title>Markdown Preview</title>
</head>
<body>
    <article class="markdown-body" id="content"></article>

    <script>
        function codeHighlight() {
            if (hljs !== undefined) {
                document.querySelectorAll('pre code').forEach((el) => {
                  hljs.highlightElement(el);
                });
            }
        }

        document.addEventListener('DOMContentLoaded', (event) => {
            document.querySelectorAll('pre code').forEach((el) => {
                hljs.highlightElement(el);
            });

            codeHighlight();

            const webSocketUrl = 'ws://' + window.location.host;
            var socket = new WebSocket(webSocketUrl);

            // Handle WebSocket events...
            socket.onmessage = function(event) {
                const message = JSON.parse(event.data);

                if (message.type === "update_content") {
                    document.getElementById('content').innerHTML = message.data;
                    codeHighlight();
                } else if (message.type === "scroll") {
                    const scrollPercent = message.data;

                    // Calculate the absolute scroll position based on the percentage
                    const windowHeight = window.innerHeight;
                    const totalScrollHeight = document.documentElement.scrollHeight - windowHeight;
                    const absoluteScrollPosition = totalScrollHeight * (scrollPercent / 100);

                    // Scroll the page to the calculated absolute position
                    window.scrollTo(0, absoluteScrollPosition);
                } else {
                    console.log(`Invalid message: {message}`)
                }
            }

            socket.onclose = function(event) {
                // Close the browser window.
                window.open('', '_self', '');
                window.close();
            }
        });
    </script>
</body>
</html>
